package com.honour.controller.interfaced;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.honour.service.interfaced.impl.DiscoverInService;
import com.system.controller.base.BaseController;
import com.system.util.AppUtil;
import com.system.util.Const;
import com.system.util.FTPUtils;
import com.system.util.PageData;
import com.system.util.Tools;
import com.system.util.ToolsUtil;
import com.system.util.UpdImgUtils;





/** 
 * 说明：发现
 * 创建人：zhaozhenhua
 * 创建时间：2017-12-05
 */
@Controller
@RequestMapping(value="/appdiscoverin")
public class DiscoverInController extends BaseController {
	
	@Resource(name="discoverinService")
	private DiscoverInService discoverinService;
	
	//头条的视频
	//public static String SHOWVIDEO="";
	
	/**
	 * 获取所有的菜单项
	 * @Author zhaozhenhua
	 * @date   2017年12月05日
	 * @return
	 */
	@RequestMapping(value="/caidan")
	@ResponseBody
	public Object sHotel(){
		logBefore(logger, "获取所有的菜单项");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("CAIDAN", pd.getString("FKEY"))){	//检验请求key值是否合法
				if (AppUtil.checkParam("shoppingCart", pd)) { // 检查参数
					 List<PageData> list = discoverinService.getCaiDanList(pd);
					 PageData topLine = discoverinService.getTopLineById(pd);
					 String DISCOVERVIDEO_IDS = topLine.getString("DISCOVERVIDEO_IDS");
					 String[] topline1 = DISCOVERVIDEO_IDS.split(",");
					 //用户订阅的头条
					 List<PageData> topline=new ArrayList<>();  
					 for (String id : topline1) {
						 PageData p = discoverinService.getCaiDanById(id);
						 topline.add(p);
					 }
					 List<PageData> recomList = discoverinService.getCaiDanList(pd);
					 recomList.removeAll(topline);
					 map.put("topline", topline);
					 map.put("recomList", recomList);
					 result = (0 == list.size()) ?  "02" :  "01";
				}else{
					result = "03";
				}	 
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 根据菜单ID获取视频和图片
	 * @Author zhaozhenhua
	 * @date   2017年12月05日
	 * @return
	 */
	@RequestMapping(value="/discoverlist")
	@ResponseBody
	public Object sGolf(){
		logBefore(logger, "根据菜单ID获取视频和图片");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("DISCOVERLIST", pd.getString("FKEY"))){	//检验请求key值是否合法
					//根据菜单ID获取视频列表
					List<PageData> list = discoverinService.getVideoListById(pd);
					for (PageData data : list) {
						 ToolsUtil.putImgstoArray(data, "VIDEOBACKIMAGE");
					}
					map.put("pd", list);
				//返回01为添加成功并返回
				result =  "01";

			}else{
				result = "05";
			}	
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 商家发布自媒体广告流
	 * @Author zhaozhenhua
	 * @date   2018年1月13日
	 * @return
	 */
	@RequestMapping(value="/addselfmediaad")
	@ResponseBody
	public Object addSelfMediaAd(MultipartHttpServletRequest mreq,
			                     HttpServletResponse resp,HttpServletRequest request,
			                     String TITLE,String HONOURUSER_ID,String DIS_TYPE,String CAIDAN_ID 
			                     ){
		logBefore(logger, "商家发布自媒体广告流");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		String VIDEOBACKIMAGE="";
		try{
			if(Tools.checkKey("SELFMEDIAADD", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(DIS_TYPE.equals("2001")){
					InputStream is = mreq.getFile("showfile").getInputStream();
					InputStream stream = mreq.getFile("fileList").getInputStream();
					//创建子线程，并启动子线程
					MySubThread runnable = new MySubThread();
					runnable.setCAIDAN_ID(CAIDAN_ID);
					runnable.setDIS_TYPE(DIS_TYPE);
					runnable.setHONOURUSER_ID(HONOURUSER_ID);
					runnable.setTITLE(TITLE);
					runnable.setMreq(mreq);
					runnable.setIs(is);
					runnable.setRequest(request);
					runnable.setResponse(resp);
					runnable.setStream(stream);
					Thread thread = new Thread(runnable);
					thread.start();
				}else{
					List<MultipartFile> fileList = mreq.getFiles("fileList");
					// 创建一个通用的多部分解析器.  
					CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
					// 设置编码  
					commonsMultipartResolver.setDefaultEncoding("utf-8");  
					// 判断是否有文件上传  
					for (MultipartFile file : fileList) {
						//String filePath = "";
						if (file!=null&&file.getOriginalFilename().length()!=0&&file.getSize()!= 0) {
							//获得UUID之后的文件名
							String imgname=UpdImgUtils.getUniqueFileName(file.getOriginalFilename());
							InputStream in = file.getInputStream();
							//获得文件全名
							try {
								resp.setCharacterEncoding("UTF-8");
								//resp.getWriter().write(filePath+";");
								//根据txt文件读取ftp工具类上传需要的参数
								String updeploy = Tools.readTxtFileAll(Const.UPDOWNLOADPATH, "UTF-8");
								String[] split = updeploy.split(",");
								//第一个参数为  图片服务器的地址
								//第二个参数为  图片服务器接口
								//第三/四个参数为  FTP服务器的登录用户名和密码
								//通过工具类获取图片服务器地址
								String imgpath = Tools.readTxtFileAll(Const.IMAGEPATH, "UTF-8");
								String path="discover/videobackimg";
								FTPUtils.uploadFile(split[0], Integer.parseInt(split[1]), split[2], split[3], path, imgname, in);
								VIDEOBACKIMAGE+=","+imgpath+path+"/"+imgname;
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
					if(VIDEOBACKIMAGE!=null&&VIDEOBACKIMAGE.length()!=0){
						pd.put("VIDEOBACKIMAGE", VIDEOBACKIMAGE.substring(1));
					}else{
						pd.put("VIDEOBACKIMAGE", "");
					}
					pd.put("DISCOVERVIDEO_ID", this.getSnowId());
					//发布时间
					Date date = new Date();
					String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
					pd.put("ADDTIME", format);
					pd.put("TITLE", TITLE);
					pd.put("SHOWVIDEO", "");
					pd.put("ISSHOW", "1");  
					pd.put("PAGEVIEWS", 0);  
					pd.put("CAIDAN_ID", CAIDAN_ID);  
					pd.put("DIS_TYPE", DIS_TYPE);    
					pd.put("HONOURUSER_ID", HONOURUSER_ID);
					discoverinService.addSelfMediaAd(pd);
				}
				
				//返回01为查询成功并返回
				result =   "01";
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 *  修改用户订阅的头条
	  * @Description
	  * @Author zhaozhenhua
	  * @date   2018年2月8日
	  * @param pd
	  * @return
	  * @throws Exception
	 */
	@RequestMapping(value="/updtopline")
	@ResponseBody
	public Object updTopLine(){
		logBefore(logger, "修改用户订阅的头条");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("UPDTOPLINE", pd.getString("FKEY"))){	//检验请求key值是否合法
				if (AppUtil.checkParam("updTopLine", pd)) { // 检查参数
					 discoverinService.updTopLine(pd);
				     result =  "01";
				} else {
					result = "03";
				}
			}else{
				result = "05";
			}
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	/**
	 * 修改头条的浏览量
	  * @Description
	  * @Author zhaozhenhua
	  * @date   2018年3月5日
	  * @param pd
	  * @return
	  * @throws Exception
	 */
	@RequestMapping(value="/updpageviews")
	@ResponseBody
	public Object updPageViews(){
		logBefore(logger, "修改头条的浏览量");
		Map<String,Object> map = new HashMap<String,Object>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String result = "00";
		try{
			if(Tools.checkKey("UPDPAGEVIEWS", pd.getString("FKEY"))){	//检验请求key值是否合法
				if(AppUtil.checkParam("updPageViews", pd)){
					PageData headTop = discoverinService.getHeadTopById(pd);
					pd.put("PAGEVIEWS", headTop.getInterger("PAGEVIEWS")+1);
					discoverinService.updPageViews(pd);
					result = "01";
				}else{
					result = "03";
				}
			}else{
				result = "05";
			}	
		}catch (Exception e){
			logger.error(e.toString(), e);
		}finally{
			map.put("result", result);
			logAfter(logger);
		}
		return AppUtil.returnObject(new PageData(), map);
	}
	
	
	
	
	
}


